﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading.Tasks;

namespace Eve.TapToClick.Core.Device
{
    class PointingDeviceManage
    {
        // 设备数量
        public int deviceNum;
        // 设备PNPDeviceID
        private ArrayList PNPDeviceIDs;

        public PointingDeviceManage()
        {
            deviceNum = 0;
            PNPDeviceIDs = new ArrayList();
        }

        // 初始化数据
        public int Initial()
        {
            deviceNum = 0;
            PNPDeviceIDs.Clear();

            ConnectionOptions opts = new ConnectionOptions();
            ManagementScope scope = new ManagementScope(@"\\.\root\cimv2", opts);
            string query = "select * from Win32_PointingDevice";
            System.Management.ObjectQuery oQuery = new ObjectQuery(query);
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, oQuery);
            ManagementObjectCollection recordSet = searcher.Get();
            deviceNum = recordSet.Count;
            foreach (ManagementObject record in recordSet)
            {
                PNPDeviceIDs.Add(record.GetPropertyValue("PNPDeviceID"));
            }
            return deviceNum;
        }

        // 获取设备数量
        public int GetDeviceNum()
        {
            return deviceNum;
        }

        // 获取索引,小于0则不存在
        private int GetDevice(String PNPDeviceID)
        {
            for(int i = 0; i < PNPDeviceIDs.Count; i++)
            {
                if (PNPDeviceIDs[i].ToString() == PNPDeviceID)
                {
                    return i;
                }
            }
            return -1;
        }

        public bool CheckDevice(String PNPDeviceID)
        {
            return GetDevice(PNPDeviceID) > -1;
        }

        public void AddDevice(String PNPDeviceID)
        {
            if(!CheckDevice(PNPDeviceID))
            {
                PNPDeviceIDs.Add(PNPDeviceID);
                deviceNum = PNPDeviceIDs.Count;
            }
        }

        public void RemoveDevice(String PNPDeviceID)
        {
            int index = GetDevice(PNPDeviceID);
            if(index != -1)
            {
                PNPDeviceIDs.RemoveAt(index);
                deviceNum = PNPDeviceIDs.Count;
            }
        }

    }
}
